package com.ctgu.elasticsearch.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.elasticsearch.config.rabbitMQ.UserQueueConfig;
import com.ctgu.elasticsearch.entity.UserEntity;
import com.ctgu.elasticsearch.service.UserService;
import com.ctgu.elasticsearch.mapper.UserMapper;
import com.ctgu.elasticsearch.utils.ApiResult;
import com.ctgu.elasticsearch.utils.PageData;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import static com.ctgu.elasticsearch.utils.Tools.buildPageData;

/**
* @author Alex2
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2025-08-13 17:20:01
*/
@Log4j2
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    private final ElasticsearchClient elasticsearchClient;
    private final RabbitTemplate rabbitTemplate;

    public UserServiceImpl(ElasticsearchClient elasticsearchClient, RabbitTemplate rabbitTemplate) {
        this.elasticsearchClient = elasticsearchClient;
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * @ Author: Alex
     * @ Description: 分词匹配
     */
    public ApiResult searchUsers(Integer pageNum, Integer pageSize, String keyword) throws IOException {
        SearchResponse<UserEntity> response = elasticsearchClient.search(s -> s
                        .index("users")
                        .query(q -> q.match(m -> m.field("username").query(keyword)))
                        .from((pageNum - 1) * pageSize)
                        .size(pageSize),
                UserEntity.class);
        return ApiResult.success("获取成功", buildPageData(response, pageSize));
    }

    /**
     * @ Author: Alex
     * @ Description: 精确匹配-高亮查询
     */
    public ApiResult searchUsersHighLight(Integer pageNum, Integer pageSize, String keyword) throws IOException {
        SearchResponse<UserEntity> response = elasticsearchClient.search(s -> s
                        .index("users")
                        .query(q -> q.term(t -> t.field("username").value(keyword)))
                        .from((pageNum - 1) * pageSize)
                        .size(pageSize)
                        .highlight(h -> h
                                .fields("username", f -> f.preTags("<em>").postTags("</em>"))
                        ),
                UserEntity.class);

        // 将高亮结果映射到新的字段 usernameHighlight
        List<UserEntity> list = response.hits().hits().stream().map(hit -> {
            UserEntity user = hit.source();
            if (hit.highlight() != null && hit.highlight().containsKey("username") && user != null) {
                user.setUsernameHighlight(String.join("", hit.highlight().get("username")));
            }
            return user;
        }).collect(Collectors.toList());

        long totalHits = response.hits().total() != null ? response.hits().total().value() : 0;
        int totalPages = (int) ((totalHits + pageSize - 1) / pageSize);

        PageData<UserEntity> pageData = PageData.<UserEntity>builder()
                .totalNum(totalHits)
                .totalPage(totalPages)
                .data(list)
                .build();

        log.debug("获取列表成功 : {}", list);
        return ApiResult.success("获取成功", pageData);
    }

    /**
     * @ Author: Alex
     * @ Description: 插入用户，mysql-elasticsearch 同步
     */
    @Override
    public ApiResult insertUser(String username, String password, Integer age) throws IOException {
        UserEntity user = lambdaQuery().eq(UserEntity::getUsername, username).one();
        if (user != null) {
            return ApiResult.error("用户已存在，插入失败");
        }
        // 插入数据库
        UserEntity userEntity = new UserEntity(null, username, password, age, null);
        save(userEntity);
        // 通过 RabbitMQ 发送给 ElasticSearch
        rabbitTemplate.convertAndSend(
                UserQueueConfig.USER_EXCHANGE,
                UserQueueConfig.INSERT_USER_ROUTING_KEY,
                userEntity
        );
        return ApiResult.success("插入成功", userEntity);
    }

    /**
     * @ Author: Alex
     * @ Description: 更新用户，mysql-elasticsearch 同步
     */
    @Override
    public ApiResult updateUser(Integer id, String username, String password, Integer age) {
        // 先更新数据库
        UserEntity userEntity = new UserEntity(id, username, password, age, null);
        boolean updated = updateById(userEntity);

        if (!updated) {
            return ApiResult.error("用户更新失败，ID不存在");
        }

        // 通过 RabbitMQ 同步更新到 ES
        rabbitTemplate.convertAndSend(
                UserQueueConfig.USER_EXCHANGE,
                UserQueueConfig.UPDATE_USER_ROUTING_KEY,
                userEntity
        );

        return ApiResult.success("用户更新成功", userEntity);
    }

    /**
     * @ Author: Alex
     * @ Description: 删除用户，mysql-elasticsearch 同步
     */
    @Override
    public ApiResult deleteUser(Integer id) throws IOException {
        boolean delete = removeById(id);
        if (!delete) {
            return ApiResult.error("用户不存在或删除失败");
        }
        rabbitTemplate.convertAndSend(
                UserQueueConfig.USER_EXCHANGE,
                UserQueueConfig.DELETE_USER_ROUTING_KEY,
                id);
        log.info("发送 RabbitMQ 消息同步删除 ES，id={}", id);
        return ApiResult.success("删除成功");
    }
}